﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ExpressionMapper.Tests
{
    [TestClass]
    public class NullableTypesTests
    {
        [TestMethod]
        public void NullableToNullableReferenceTest()
        {
            int? i = 5;
            var m = Mapper.Create<int?, int?>();
            int? j = m(i);
            Assert.IsFalse(ReferenceEquals(i,j));
            Assert.IsTrue(j.HasValue);
            Assert.AreEqual(i.Value, j.Value);
        }

        [TestMethod]
        public void ConvertToNullable()
        {
            var m = Mapper.Create<short, short?>();
            var r = m(5);
            Assert.IsTrue(r.HasValue);
            Assert.AreEqual(5, r.Value);
        }


        [TestMethod]
        public void ConvertToNullableDifferentTypes()
        {
            // should not fail. Can actually use (double?)(x) => Convert.ToDouble(x)
            double? result = Convert.ToDouble(1);
            Assert.IsTrue(result.HasValue);
            Assert.AreEqual(1, result);
            
            var m = Mapper.Create<int, double?>();
            var r = m(1);
            Assert.IsTrue(r.HasValue);
            Assert.AreEqual(1, r.Value);
        }

        [TestMethod]
        public void ConvertFromNullableDifferentTypes()
        {
            // should not fail. Can actually use (double?)(x) => Convert.ToDouble(x)
            double? result = Convert.ToDouble(1);
            Assert.IsTrue(result.HasValue);
            Assert.AreEqual(1, result);

            var m = Mapper.Create<int?, double>();
            var r = m(1);
            Assert.AreEqual(1, r);

            r = m(null);
            Assert.AreEqual(0,r);
        }

        [TestMethod]
        public void ConvertFromNullable()
        {
            var m = Mapper.Create<int?, int>();
            var r = m(1);
            Assert.AreEqual(1,r);
        }

        [TestMethod]
        public void ConvertFromNullableNullThrows()
        {
            var m = Mapper.Create<int?, int>();
            var result = m(null);
            Assert.AreEqual(0, result);
        }

    }
}
